/*
 Copyright 2014 Alexander V. Nikulin
 
 Licensed under the Apache License, Version 2.0 (the "License");
 you may not use this file except in compliance with the License.
 You may obtain a copy of the License at
	
 	http://www.apache.org/licenses/LICENSE-2.0
	
 Unless required by applicable law or agreed to in writing, software
 distributed under the License is distributed on an "AS IS" BASIS,
 WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 See the License for the specific language governing permissions and
 limitations under the License.
*/
package ru.avn.adf;

import java.lang.reflect.Constructor;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
/**
 * @author Alexander V. Nikulin
 */
public class ReflectionUtils {

	public static String getSetterName(Field field) {
		return getSetterName(field.getName());
	}
	
	public static String getGetterName(Field field) {
		return getGetterName(field.getName());
	}
	
	public static String getGetterName(String name) {
		char[] chars = name.toCharArray();
		chars[0] = Character.toUpperCase(chars[0]);
		return "get" + new String(chars);
	}
	
	public static String getSetterName(String name) {
		char[] chars = name.toCharArray();
		chars[0] = Character.toUpperCase(chars[0]);
		return "set" + new String(chars);
	}
	
	public static String getPropertyName(Method method) {
		String propertyName = null;
		
		String methodName = method.getName();
		if (methodName.startsWith("get") || methodName.startsWith("set")) {
			char[] chars = methodName.substring(3).toCharArray();
			chars[0] = Character.toLowerCase(chars[0]);
		} else{
			propertyName = methodName;
		}
		
		return propertyName;
	}
	
	public static Method getGetter(PayloadDeclaration<?> declaration) {
		Method method = null;
		
		try {
			method = declaration.getContainerType()
					.getMethod(getGetterName(declaration.getName()));
		} catch (NoSuchMethodException e) {}
		
		return method;
	}
	
	public static Method getSetter(PayloadDeclaration<?> declaration) {
		Method method = null;
		
		try {
			method = declaration.getContainerType()
					.getMethod(getSetterName(declaration.getName()), declaration.getType());
		} catch (NoSuchMethodException e) {}
		
		return method;
	}

	public static  <T> T newInstance(Class<T> classType) {
		try {
			return classType.newInstance();
		} catch (Exception e) {
			throw new RuntimeException(e);
		}
	}
	
	public static <T> T newInstance(Class<T> classType, Object[] args, Class<?>[] types) {
		try {
			Constructor<T> constructor = classType.getConstructor(types);
			return constructor.newInstance(args);
		} catch (Exception e) {
			throw new RuntimeException(e);
		}
	}
	
}
